package co.yixiang.common.security.config;

import cn.hutool.core.map.MapUtil;
import co.yixiang.common.core.constant.SecurityConstants;
import co.yixiang.common.security.domain.JwtUser;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
import org.springframework.util.StringUtils;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * https://my.oschina.net/giegie/blog/3023768 根据checktoken 的结果转化用户信息
 *
 * @author lengleng
 */
public class CommonUserConverter implements UserAuthenticationConverter {
    private static final String N_A = "N/A";

    private UserDetailsService userDetailsService;

    public CommonUserConverter(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    /**
     * 将授权信息返回到资源服务
     */
    @Override
    public Map<String, ?> convertUserAuthentication(Authentication userAuthentication) {
        Map<String, Object> authMap = new LinkedHashMap<>();
        authMap.put(USERNAME, userAuthentication.getName());
        authMap.put("id", ((JwtUser) userAuthentication.getPrincipal()).getId());
        if (userAuthentication.getAuthorities() != null && !userAuthentication.getAuthorities().isEmpty()) {
            authMap.put(AUTHORITIES, AuthorityUtils.authorityListToSet(userAuthentication.getAuthorities()));
        }
        return authMap;
    }

    /**
     * 获取用户认证信息
     */
    @Override
    public Authentication extractAuthentication(Map<String, ?> responseMap)
    {
        if (responseMap.containsKey(USERNAME))
        {
            Collection<? extends GrantedAuthority> authorities = getAuthorities(responseMap);
            Collection<SimpleGrantedAuthority> simpleGrantedAuthorities = authorities.stream()
                    .map(a->( new SimpleGrantedAuthority(a.getAuthority()))).collect(Collectors.toList());
            Map<String, ?> userInfo = MapUtil.get(responseMap, SecurityConstants.DETAILS_USER, Map.class);
            String username = MapUtil.getStr(userInfo, SecurityConstants.DETAILS_USERNAME);
            Long userId = MapUtil.getLong(userInfo, SecurityConstants.DETAILS_USER_ID);
            Integer retail = MapUtil.getInt(userInfo, SecurityConstants.DETAILS_RETAIL);
            Integer retailType = MapUtil.getInt(userInfo, SecurityConstants.DETAILS_RETAILTYPE);
            Integer permit = MapUtil.getInt(userInfo, SecurityConstants.DETAILS_PERMIT);
            JwtUser user = new JwtUser(userId, username, "", "","","","","","","", retail,retailType,permit,simpleGrantedAuthorities,
                    true, null, null);
            return new UsernamePasswordAuthenticationToken(user, N_A, authorities);
        }
        return null;
    }
    /**
     * 获取权限资源信息
     */
    private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
        Object authorities = map.get(AUTHORITIES);
        if (authorities instanceof String) {
            return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);
        }
        if (authorities instanceof Collection) {
            return AuthorityUtils.commaSeparatedStringToAuthorityList(
                    StringUtils.collectionToCommaDelimitedString((Collection<?>) authorities));
        }
        throw new IllegalArgumentException("Authorities must be either a String or a Collection");
    }
}
